package main

import (
	"fmt"
	"sort"
	"strings"
)

func main() {
	// map为引用类型
	// 1、 make创建map类型的数据

	var userInfo = make(map[string]string)
	userInfo["name"] = "zs"
	userInfo["age"] = "18"
	fmt.Println(userInfo) //map[age:18 name:zs]

	//2、声明时初始化值
	userInfo2 := map[string]string{
		"username": "ls",
		"age":      "21",
	}
	fmt.Println(userInfo2) //map[age:21 username:ls]

	//3、循环遍历map类型数据
	for k, v := range userInfo2 {
		fmt.Printf("key:%v,value:%v\n", k, v)
		/*
			key:username,value:ls
			key:age,value:21
		*/
	}

	//4、map类型数据的curd
	userInfo3 := make(map[string]string)
	userInfo3["name"] = "zw" //增
	userInfo3["name"] = "qw" //改

	v, ok := userInfo3["age"] //查
	fmt.Println(v, ok)        // 空  false

	delete(userInfo3, "name")
	fmt.Println(userInfo3) // map[]

	//5、map类型的切片 map不初始化值为nil
	var people = make([]map[string]string, 3, 3) // map类型切片
	fmt.Println(people[0])                       // map[]  不初始化值 默认值时nil
	fmt.Println(people[0] == nil)                // true
	if people[0] == nil {
		people[0] = make(map[string]string)
		people[0]["name"] = "ls"
		people[0]["age"] = "21"
	}
	for k, v := range people {
		fmt.Println("k=", k, "v=", v)
	}
	/*
		k= 0 v= map[age:21 name:ls]
		k= 1 v= map[]
		k= 2 v= map[]
	*/
	//6、map类型存放多多值类型
	var course = make(map[string][]string)
	course["java"] = []string{"springMVC", "myBatis", "odbc"}
	course["javascript"] = []string{"nodejs", "vue", "react"}
	for k, v := range course {
		fmt.Println("k=", k, "v=", v)
	}
	/*
		k= java v= [springMVC myBatis odbc]
		k= javascript v= [nodejs vue react]
	*/

	//7、map的排序
	map1 := make(map[int]int, 10)
	map1[10] = 100
	map1[4] = 43
	map1[6] = 50
	map1[1] = 13
	fmt.Println(map1) //map[1:200 2:43 3:50 4:13]
	for k, v := range map1 {
		fmt.Println("k=", k, "v=", v)
	}
	/*     map遍历的值是随机的  不会从第一项开始 比如 map[1]
			   k= 4 v= 43
		       k= 6 v= 50
		       k= 1 v= 13
	       	   k= 10 v= 100
	*/

	//疑问？如何实现按照key升序排序呢
	//1、把map的key放在切片里
	var slice []int
	for k, _ := range map1 {
		slice = append(slice, k)
	}
	fmt.Println(slice) // [10 4 6 1]
	//2、让key进行升序排序
	sort.Ints(slice)
	fmt.Println(slice, "slice")
	//循环slice输出map对应key值
	for _, v := range slice {
		fmt.Printf("%v\t", map1[v]) //13 43 50 100
	}

	//8、字符串 split分割成切片
	var str = "so beautiful you are, cute girl!"
	var sliceStr = strings.Split(str, " ") //使用strings包 分割str生产切片，以空格分割
	fmt.Println(sliceStr)                  // [so beautiful you are, cute girl!]

}
